package com.adobe.growl.tests
{
	import flexunit.framework.TestCase;
	import com.adobe.growl.GrowlService;
	import com.adobe.growl.Application;
	import com.adobe.growl.events.GrowlConnectionEvent;
	import flash.events.IOErrorEvent;
	import com.adobe.growl.events.GrowlResponseEvent;
	import flash.filesystem.File;
	import com.adobe.growl.events.GrowlErrorEvent;

	public class GrowlServiceTest extends TestCase
	{
		private var gs:GrowlService;
		private var application:Application;
		public function GrowlServiceTest(methodName:String=null)
		{
			super(methodName);
			
			
			application = new Application();
			application.name = "Application Name";
			//application.iconPath = new File(new File("app:/icon.png").nativePath).url;
			gs = new GrowlService(application);
		}
		
		/*********** TEST CONNECTION ***************/
		public function testConnection():void
		{
			
			//note, this does not work if Growl is not running. Wrong methods are
			//called with wrong arguments due to flexunit bug:
			//http://www.adobeforums.com/webx/.59b700e8/
			gs.addEventListener(GrowlConnectionEvent.CONNECT, 
													addAsync(onConnect, 1000, null, onConnectTimeout));
													
			gs.addEventListener(GrowlResponseEvent.REGISTER,
										addAsync(onConnectRegister, 1000, null, onRegistrationTimeout));
										
			gs.addEventListener(GrowlErrorEvent.REGISTRATION_ERROR,
										addAsync(onConnectRegisterError, 1000, null, doNothing));
					
			gs.addEventListener(IOErrorEvent.IO_ERROR,
													addAsync(onConnectError, 1000, null, doNothing));					
														
			gs.connect();
		}
		
		//the arguments are to work around a flexunit bug
		private function doNothing(foo:*=null):void
		{
		}
		
		private function onConnectTimeout():void
		{
			fail("connect timed out");
		}		
		
		private function onRegistrationTimeout():void
		{
			fail("registration timed out");
		}
		
		private function onConnect(e:GrowlConnectionEvent):void
		{
			assertTrue("gs.connected == true", gs.connected);
			assertTrue("e.application == application", (e.application == application));
		}
		
		private function onConnectError(e:IOErrorEvent):void
		{
			fail("Connection to Growl failed : " +  e.text);
		}
		
		private function onConnectRegister(e:GrowlResponseEvent):void
		{
			assertTrue("e.application == application", (e.application == application));
		}
		
		private function onConnectRegisterError(e:GrowlErrorEvent):void
		{
			assertTrue("e.application == application", (e.application == application));
			fail("Registration to Growl failed : " + "[" + e.code + "] " + e.message);
		}		
		
		/*********** END TEST CONNECTION ***************/
		
		public function testApplication():void
		{
			assertTrue("gs.application == application", (gs.application == application));
		}
	}
}